<template>
    <div class="pdf-box">
        <div class="pdf-body">
            <pdf ref="pdfDoc" :src="pdfSrc" :page="currentPage" @num-pages="onPdfLoaded" @error="pdfError" @progress="onProgress" />
        </div>
        <div class="pdf-footer">
            <el-button type="primary" size="mini" @click="goToPreviousPage">上一页</el-button>
            <span style="margin: 5px 10px;">{{ currentPage }} / {{ totalPages }}</span>
            <el-button type="primary" size="mini" @click="goToNextPage">下一页</el-button>
            <el-button type="primary" size="mini" @click="doPrint">打印</el-button>
        </div>
    </div>
</template>

<script>
import pdf from "vue-pdf";
export default {
    components: {
        pdf,
    },
    props: {
        PDFSrc: {
            type: String,
            default: ''
        }
    },
    watch: {
        PDFSrc: {
            handler(newVal,oldVal){
                this.pdfSrc = newVal;
            },
            immediate: true
        }
    },
    data() {
        return {
            pdfSrc: '',
            currentPage: 1,
            totalPages: 0,
        };
    },
    mounted() {
    },
    methods: {
        // 处理 PDF 加载完成事件
        onPdfLoaded(pdfData) {
            this.totalPages = pdfData;
        },
        goToNextPage() {
            if (this.currentPage === this.totalPages) return;
            this.currentPage += 1;
        },
        goToPreviousPage() {
            if (this.currentPage === 1) return;
            this.currentPage -= 1;
        },
        onProgress(progress) {
            console.log("Loading progress: ", progress);
        },
        pdfError(error) {
            console.error(error);
        },
        async doPrint(){
            const response = await fetch(this.pdfSrc);
            const blob = await response.blob();

            let idx = this.pdfSrc.lastIndexOf("/") + 1;
            let fileName = this.pdfSrc.substring(idx);
            let url = URL.createObjectURL(blob);
            let a = document.createElement('a');
            a.href = url;
            a.download = fileName;
            a.click();

            URL.revokeObjectURL(url);
            document.removeChild(a);
        }
    },
};
</script>

<style lang="scss" scoped>
.pdf-box {
    position: relative;
    // float: right;
    padding: 10px;
    width: 100%;
    height: 100%;
    overflow-x: hidden;
    overflow-y: scroll;

    .pdf-body {
        height: 100%;
        overflow: hidden;
    }

    .pdf-footer {
        position: absolute;
        margin-top: -50px;
        width: 100%;
        padding: 5px 0px;
        border-radius: 4px;
        display: flex;
        justify-content: center;
        align-content: center;
        background: rgba(255,255,255,0.4);
    }
}
</style>
